package com.mysteel.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.mysteel.authserver.feign.MemberFeignService;
import com.mysteel.authserver.feign.ThirdPartFeignService;
import com.mysteel.authserver.vo.UserLoginVo;
import com.mysteel.authserver.vo.UserRegisterVo;
import com.mysteel.common.constant.AuthServerConstant;
import com.mysteel.common.exception.BizCodeEnum;
import com.mysteel.common.utils.ParameterErrorHandlerUtil;
import com.mysteel.common.utils.R;
import com.mysteel.common.vo.MemberResponseVo;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * ProjectName: mail
 * ClassName: LoginController
 * Description:
 * date: 2021/02/22/022 11:51
 *
 * @author xiaochao
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        // 60秒防盗刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.REG_VALIDATE_CODE_KEY + phone);
        if (StringUtils.isNotBlank(redisCode)){
            Long sendCodeTime = Long.valueOf(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - sendCodeTime < 60000){
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = RandomStringUtils.randomNumeric(6);

        // redis缓存验证码，10分钟有效
        redisTemplate.opsForValue().set(AuthServerConstant.REG_VALIDATE_CODE_KEY + phone,code + "_" + System.currentTimeMillis(),10L, TimeUnit.MINUTES);

        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    @GetMapping("/login.html")
    public String toLogin(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER_DATA);
        if (Objects.isNull(attribute)){
            return "login";
        }
        return "redirect:http://xcmail.com";
    }

    @PostMapping("/register")
    public String register(@Validated UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        Map<String, String> errors = new HashMap<>();
        if (result.hasErrors()){
            errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            // 检验出错转发到注册页
            return "redirect:http://auth.xcmail.com/reg.html";
        }
        // 校验验证码
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.REG_VALIDATE_CODE_KEY + vo.getPhone());
        if (StringUtils.isBlank(redisCode)){
            // 验证码未发送
            errors.put("msg","验证码未发送");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.xcmail.com/reg.html";
        }else {
            String strCode = redisCode.split("_")[0];
            if (!strCode.equals(vo.getCode())){
                errors.put("msg","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.xcmail.com/reg.html";
            }
            // 走注册流程
            R feignResult = memberFeignService.registerUser(vo);
            if (feignResult.getCode() == 0){
                // 注册成功跳登录页,删除验证码缓存
                redisTemplate.delete(AuthServerConstant.REG_VALIDATE_CODE_KEY + vo.getPhone());
                return "redirect:http://auth.xcmail.com/login.html";
            }else {
                errors.put("msg",feignResult.getMsg());
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.xcmail.com/reg.html";
            }
        }
    }

    @PostMapping("/login")
    public String login(@Validated UserLoginVo loginVo, BindingResult result, RedirectAttributes redirectAttributes, HttpSession session){
        Map<String, String> errors;
        errors = ParameterErrorHandlerUtil.handleException(result);
        if (!CollectionUtils.isEmpty(errors)){
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.xcmail.com/login.html";
        }
        // 远程登录
        R feignResult = memberFeignService.userLogin(loginVo);
        if (feignResult.getCode() != 0){
            // 登录失败
            errors.put("msg",feignResult.getMsg());
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.xcmail.com/login.html";
        }
        MemberResponseVo userInfo = feignResult.getData("userInfo", new TypeReference<MemberResponseVo>() {
        });
        session.setAttribute(AuthServerConstant.LOGIN_USER_DATA,userInfo);
        return "redirect:http://xcmail.com";
    }
}
